<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn()">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list" :key="index">
          <td>{{index+1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="removeFn(index)">删除</button>
            <button @click="alterFn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      list:[
        {
            // id:this.list.length?this.list[this.list.length-1].id+1:0,
          // id:this.list.length==0?this.list[this.list.length-1].id+1:0,
          name:"小白",
          age:18,
          gender:"男"
          }
      ],
      name:'',
      age:"",
      gender:"",
      flag:false,
      index:""
    }
  },
  methods:{
    // 增加/编辑
    addFn(){
      // console.log(this.name,this.age,this.gender)
      // if(this.list.every((item,index)=>item.id==this.id)){
      //   console.list(71)
      // //   this.name=this.list[index].name
      // // this.age=this.list[index].age
      // // this.gender=this.list[index].gender
      // // this.id=this.list[index].id
      // }else{
          // }
        if(this.name==''||this.age==""||this.gender==""){
        alert('信息不可为空')
        return
      }

      if(this.flag){
        this.list[this.index].name=this.name
        this.list[this.index].age=this.age
        this.list[this.index].gender=this.gender
        this.flag="false"
      }else{
      this.list.push({name:this.name,age:this.age,gender:this.gender})
      }
    
      
      this.name=''
      this.age=""
      this.gender=""
    },
    // 删除
    removeFn(index){
      this.list.splice(index,1)
    },
    // 编辑
    alterFn(index){
      this.name=this.list[index].name
      this.age=this.list[index].age
      this.gender=this.list[index].gender
      this.flag=!this.show
      this.index=index
    }
  }
}
</script>
